package com.yloveg.base;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import java.io.*;

import com.yloveg.common.DateUtil;

public class ImageToBase64ToImage {
	//base64字符串转化成图片
    public static String Base64ToImage(String imgStr,String img_path,String linux_url){
		/* imgStr = imgStr.replace("data:image/jpeg;base64,",""); */
    	String str1=imgStr.substring(0, imgStr.indexOf(","));
    	imgStr=imgStr.substring(str1.length()+1, imgStr.length());
    	System.out.println(imgStr);
	    String kzm=".png";
	    //扩展名
	    String path=null;
		// 保存文件路径
		String showPath=null;
		// 显示文件路径
		String prefix=null;
		String tempPath = DateUtil.endFileDir();
		path = img_path+tempPath+ "/"+ DateUtil.transPath()+kzm;
		prefix = linux_url+tempPath+ "/"+ DateUtil.transPath()+kzm;
		File f=new File(img_path+tempPath);
		f.setWritable(true, false);
		f.mkdirs();
        InputStream in = null;
		File saveFile = new File(path);
        //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) //图像数据为空
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        try{
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for(int i=0;i<b.length;++i){
                if(b[i]<0){//调整异常数据
                    b[i]+=256;
                }
            }
            OutputStream out = new FileOutputStream(saveFile);
            out.write(b);
            out.flush();
            out.close();
            System.out.println("成功");
            return prefix;
        }catch (Exception e){
        	e.printStackTrace();
        	System.out.println("失败");
        	prefix="失败";
        }
		return prefix;
    }
}